package com.cmict.data.form.api.util;

import com.cmict.data.form.api.entity.PictureDataEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RefreshScope
public class ExcelPictureUtil {

    @Value("${platform.fileupload.upload-folder}")
    private static String uploadFolder ;

    /**
     * 获取图片和位置 (xlsx)
     * @param sheet
     * @return List
     */
    public static List<PictureDataEntity> getXSSFPictures (XSSFSheet sheet) {
        List<POIXMLDocumentPart> list = sheet.getRelations();
        List<PictureDataEntity> returnList = new ArrayList<>();
        for (POIXMLDocumentPart part : list) {
            if (part instanceof XSSFDrawing) {
                XSSFDrawing drawing = (XSSFDrawing) part;
                List<XSSFShape> shapes = drawing.getShapes();
                for (XSSFShape shape : shapes) {
                    XSSFPicture picture = (XSSFPicture) shape;
                    XSSFClientAnchor anchor = picture.getPreferredSize();
                    CTMarker marker = anchor.getFrom();
                    PictureDataEntity pictureDataEntity = new PictureDataEntity();
                    pictureDataEntity.setRow(marker.getRow());
                    pictureDataEntity.setCol(marker.getCol());
                    pictureDataEntity.setXSSFPictureData(picture.getPictureData());
                    returnList.add(pictureDataEntity);
                }
            }
        }
        return returnList;
    }

    /**
     * 获取图片和位置 (xls)
     * @param sheet
     * @return List
     */
    public static List<PictureDataEntity> getHSSFPictures (HSSFSheet sheet) {
        List<HSSFShape> list = sheet.getDrawingPatriarch().getChildren();
        List<PictureDataEntity> returnList = new ArrayList<>();
        for (HSSFShape shape : list) {
            if (shape instanceof HSSFPicture) {
                HSSFPicture picture = (HSSFPicture) shape;
                HSSFClientAnchor cAnchor = picture.getClientAnchor();
                HSSFPictureData pdata = picture.getPictureData();
                PictureDataEntity pictureDataEntity = new PictureDataEntity();
                pictureDataEntity.setRow(cAnchor.getRow1());
                pictureDataEntity.setCol(cAnchor.getCol1());
                pictureDataEntity.setHSSFPictureData(pdata);
                returnList.add(pictureDataEntity);
            }
        }
        return returnList;
    }

//    public static Map<String,String> fileUpload(MultipartFile file) {
//        Map<String,String> map = new HashMap<>();
//        //file.getSize()>1048576
//        if (file.isEmpty()) {
//            System.out.println("文件为空");
//        }
//        String fileName = file.getOriginalFilename();  // 文件名
//        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
//        //String filePath = uploadUrl + uploadFolder; // 上传后的路径
//        String newFileName = UUID.randomUUID() + suffixName; // 新文件名
//        File dest = new File(uploadFolder + newFileName);
//        if (!dest.getParentFile().exists()) {
//            dest.getParentFile().mkdirs();
//        }
//        try {
//            file.transferTo(dest);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        map.put("name",fileName);
//        map.put("url",uploadUrl + newFileName);
//        return map;
//    }

    public static String getPictureData(int row, int col,List<PictureDataEntity> list){
        String url = "";
        for (PictureDataEntity pictureDataEntity:list) {
            if(pictureDataEntity.getRow() == row && pictureDataEntity.getCol() == col){
                try{
                    if(pictureDataEntity.getXSSFPictureData() != null){
                        url = printXSSFImg(pictureDataEntity.getXSSFPictureData());
                    }else{
                        url = printHSSFImg(pictureDataEntity.getHSSFPictureData());
                    }
                }catch (IOException exception){
                    log.error("表单数据Excel导入图片上传报错："+exception.getMessage());
                }
            }
        }
        return url;
    }

    /**
     * HSSF图片保存
     * @param hSSFPictureData
     * @return String
     * @throws IOException
     */
    public static String printHSSFImg(HSSFPictureData hSSFPictureData) throws IOException {
            // 获取图片所在行的指定单元格数据
            //String picName = key[i].toString();
            String picName = UUIDUtils.gen32UUID();
            byte[] data = hSSFPictureData.getData();
            // 图片保存路径
            FileOutputStream out = new FileOutputStream(uploadFolder + picName + ".jpg");
            out.write(data);
            out.close();
            return uploadFolder + picName + ".jpg";
    }

    /**
     * XSSF图片保存
     * @param xSSFPictureData
     * @return String
     * @throws IOException
     */
    public static String printXSSFImg(XSSFPictureData xSSFPictureData) throws IOException {
            // 获取图片所在行的指定单元格数据
            //String picName = key[i].toString();
            String picName = UUIDUtils.gen32UUID();
            byte[] data = xSSFPictureData.getData();
            // 图片保存路径
            FileOutputStream out = new FileOutputStream(uploadFolder + picName + ".jpg");
            out.write(data);
            out.close();
            return uploadFolder + picName + ".jpg";
    }
}
